package com.example.javabighw.controller;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.example.javabighw.dao.UserDao;
import com.example.javabighw.entity.User;

@RestController
public class SessionController {
    @Autowired
    UserDao userDao;

    @ResponseBody
    @PostMapping("/sessionKey")
    public HashMap<String, Object> sessionKey(@RequestParam(required = false, name = "sessionKey") String skey) {
        HashMap<String, Object> ret = new HashMap<>();
        System.out.println(skey);
        if (!isSessionKeyExist(skey)) {
            skey = SessionUtils.randomSessionKey();
        } else if (isSessionExpired(skey)) {
            User user = userDao.getUserBySessionKey(skey);
            skey = SessionUtils.randomSessionKey();
            user.setSessionKey(skey);
            // update the session key of the user
            userDao.updateUser(user);
        }
        ret.put("sessionKey", skey);
        return ret;
    }

    private boolean isSessionExpired(String skey) {
        User user = userDao.getUserBySessionKey(skey);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime lastTime = user.getLastTime();
        Duration different = Duration.between(now, lastTime);

        long diffHours = different.toHours();

        if (diffHours > 24) {
            return true;
        }

        return false;
    }

    private boolean isSessionKeyExist(String skey) {
        return userDao.isExistBySessionKey(skey);
    }

    public static String randomSessionKey() {
        return SessionUtils.randomSessionKey();
    }

}

class SessionUtils {
    public static String randomSessionKey() {
        // Use uuid as a session key
        return UUID.randomUUID().toString();
    }
}
